
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.paginators import MyPage
from meiduo_admin.serializers.spu_serializers import *


# 新建SPU可选分类视图
class SPUCateListView(ListAPIView):
    queryset = GoodsCategory.objects.all()
    serializer_class = SPUCateSimpleModelSerializer
    pagination_class = None

    def get_queryset(self):
        parent_id = self.kwargs.get('pk')
        # 如果请求接口是子级分类，那么根据路径父级分类id过滤出子级分类查询集返回
        if parent_id:
            return self.queryset.filter(parent_id=parent_id)
        # 如果请求接口是一级分类，那么直接过滤一级分类查询集返回
        return self.queryset.filter(parent=None) # 一级分类



# Brand列表视图
class BrandSimpleView(ListAPIView):
    queryset = Brand.objects.all()
    serializer_class = BrandSimpleModelSerializer
    pagination_class = None

# SPU视图
class SPUView(ModelViewSet):
    queryset = SPU.objects.all()
    serializer_class = SPUModelSerializer
    pagination_class = MyPage

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            return self.queryset.filter(name__contains=keyword)
        return self.queryset.all()